﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GameView.Comment;
using GameView.Services.Comment;
using GameView.Services.Dtos.Persons;
using MaterialDesignThemes.Wpf;
using System.ComponentModel.DataAnnotations;

namespace GameView.ViewModels
{
    public partial class ReSetPasswordViewModel : ObservableValidator
    {
        private readonly UserService _userService;

        public ReSetPasswordViewModel(UserService userService)
        {
            _userService = userService;
        }

        [ObservableProperty]
        private bool _isLoading = false;

        [Required(ErrorMessage = "原始密码不能为空")]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        [ObservableProperty]
        private string _oldPassword1 = string.Empty;

        [Required(ErrorMessage = "原始密码不能为空")]
        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        private string _oldPassword2 = string.Empty;

        [Required(ErrorMessage = "密码不能为空")]
        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        [MinLength(6, ErrorMessage = "密码长度不能小于6")]
        private string _newPassword = string.Empty;

        [RelayCommand(CanExecute = nameof(CanSubmit))]
        private async Task Submit()
        {
            IsLoading = true;
            try
            {
                if (OldPassword1 != OldPassword2)
                {
                    GlobalMessage.Instance.ShowError("两次输入的密码不一致，请重新输入！");
                }
                var res = await _userService.ResetPassword(new ResetPasswordEntity() { OldPassword2 = OldPassword2, OldPassword1 = OldPassword1, NewPassword = NewPassword });
                if (res.StatusCode == 200 && res.Data)
                {
                    GlobalMessage.Instance.ShowSuccess("密码修改成功！");
                    DialogHost.CloseDialogCommand.Execute(null, null);
                }
                else
                    GlobalMessage.Instance.ShowWarning($"密码修改失败！\n{JSON.Serialize(res.Errors)}");
            }
            catch (Exception rx)
            {
                GlobalMessage.Instance.ShowError(rx.Message);
            }
            finally
            {
                IsLoading = false;
            }
        }

        private bool CanSubmit() => !OldPassword1.IsNullOrEmpty() && !OldPassword2.IsNullOrEmpty() && !NewPassword.IsNullOrEmpty() && NewPassword.Length >= 6;
    }
}